package com.wlw.admin.openeye.view

import android.content.Context
import android.graphics.drawable.Drawable
import android.support.v4.content.res.ResourcesCompat
import android.text.Editable
import android.text.TextWatcher
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import android.widget.EditText
import com.wlw.admin.openeye.R

class ClearEditText @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null,
                                              defStyle: Int = android.R.attr.editTextStyle) : EditText(context, attrs, defStyle), View.OnFocusChangeListener, TextWatcher {

    private var mClearDrawable: Drawable? = null
    private var hasFocus: Boolean = false

    init {
        init()
    }

    private fun init() {
        mClearDrawable = compoundDrawables[2]
        if (mClearDrawable == null) {
            mClearDrawable = ResourcesCompat.getDrawable(resources, R.mipmap.ic_action_clear, context.theme)
        }
        mClearDrawable?.apply {
            setBounds(0, 0, intrinsicWidth, intrinsicHeight)
        }
        setClearIconVisible(false)
        onFocusChangeListener = this
        addTextChangedListener(this)
    }

    override fun onTouchEvent(event: MotionEvent?): Boolean {
        event?.let {
            if (it.action == MotionEvent.ACTION_UP) {
                if (compoundDrawables[2] != null) {
                    val x = event.x.toInt()
                    val y = event.y.toInt()
                    val rect = compoundDrawables[2].bounds
                    val height = rect.height()
                    val distance = (getHeight() - height) / 2
                    val isInnerWidth = x > width - totalPaddingRight && x < width - paddingRight
                    val isInnerHeight = y > distance && y < distance + height
                    if (isInnerWidth && isInnerHeight) {
                        this.setText("")
                    }
                }
            }
        }
        return super.onTouchEvent(event)
    }

    override fun onFocusChange(v: View?, hasFocus: Boolean) {
        this.hasFocus = hasFocus
        if (hasFocus)
            setClearIconVisible(text.isNotEmpty())
        else
            setClearIconVisible(false)
    }

    private fun setClearIconVisible(b: Boolean) {
        val right = if (b) mClearDrawable else null
        setCompoundDrawables(compoundDrawables[0],
                compoundDrawables[1], right, compoundDrawables[3])

    }

    override fun afterTextChanged(p0: Editable?) {
    }

    override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
    }

    override fun onTextChanged(text: CharSequence?, start: Int, lengthBefore: Int, lengthAfter: Int) {
        super.onTextChanged(text, start, lengthBefore, lengthAfter)
        if (hasFocus) {
            setClearIconVisible(text?.isNotEmpty()!!)
        }
    }
}

